package ${package}.rss.service;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import ${package}.rss.dao.IRssEntryDAO;
import ${package}.rss.model.RssEntry;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;

/**
 *Read RSS feed from rss source, and populate the new entry list.
 * 
 * @author Ke CAI
 */
public class RssServiceImpl implements IRssService {
	List<RssEntry> entries = new ArrayList<RssEntry>();
	private IRssEntryDAO rssEntryDAO;

	private IRssChannelService rssChannelService;

	public void setRssEntryDAO(IRssEntryDAO rssEntryDAO) {
		this.rssEntryDAO = rssEntryDAO;
	}

	public void setRssChannelService(IRssChannelService rssChannelService) {
		this.rssChannelService = rssChannelService;
	}

	public List<SyndEntry> fetchRssEntries() throws IllegalArgumentException,
			MalformedURLException, IOException, FeedException, FetcherException {
		List<String> rssChannels = rssChannelService.loadRssChannelList();

		return fetchRssEntriesFromChannels(rssChannels);
	}

	public SyndFeed loadRss(String channelUrl) throws IllegalArgumentException,
			MalformedURLException, IOException, FeedException, FetcherException {
		FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();

		FeedFetcher feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
		SyndFeed feed = feedFetcher.retrieveFeed(new URL(channelUrl));

		return feed;
	}

	public List<SyndEntry> fetchRssEntriesFromChannels(List<String> channelUrls)
			throws IllegalArgumentException, MalformedURLException,
			IOException, FeedException, FetcherException {
		List<SyndEntry> rssEntries = new ArrayList<SyndEntry>();

		for (String rssChannel : channelUrls) {

			SyndFeed feed = this.loadRss(rssChannel);
			Iterator ite = feed.getEntries().iterator();
			while (ite.hasNext()) {
				SyndEntry entry = (SyndEntry) ite.next();
				rssEntries.add(entry);

			}

		}

		return rssEntries;
	}

}
